"use strict";
const { Model } = require("sequelize");
const moment = require("moment/moment");
const { IdGenerator } = require("../utils/idGenerator");
moment.locale("zh-cn");
module.exports = (sequelize, DataTypes) => {
  class Chapter extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      // 章节关联课程
      models.Chapter.belongsTo(models.Course, {
        as: "course",
      });
      models.Chapter.hasOne(models.Attachment, {
        as: "attachments",
        foreignKey: "businessId",
      });
    }
  }

  Chapter.init(
    {
      id: {
        type: DataTypes.INTEGER.UNSIGNED, // 无符号整数类型
        allowNull: false,
        primaryKey: true,
        defaultValue: function () {
          return IdGenerator.getNextID(); // 使用封装的ID生成方法
        },
      },
      courseId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
          notNull: { msg: "课程ID必须填写。" },
          notEmpty: { msg: "课程ID不能为空。" },
          async isPresent(value) {
            const course = await sequelize.models.Course.findByPk(value);
            if (!course) {
              throw new Error(`ID为:${value}的课程不存在。`);
            }
          },
        },
      },
      title: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notNull: { msg: "标题必须填写。" },
          notEmpty: { msg: "标题不能为空。" },
          len: { args: [2, 45], msg: "标题长度必须是2~45之间。" },
        },
      },
      content: DataTypes.TEXT,
      video: {
        type: DataTypes.STRING,
        validate: {
          isUrl: { msg: "视频地址不正确。" },
        },
        get() {
          const attachments = this.getDataValue("attachments");
          if (attachments && attachments.id) {
            return (
              `${process.env.SERVER_REQUEST_ADDRESS}/api/upload/attachments/getTeamOfVideo?id=` +
              attachments.id
            );
          } else {
            return null;
          }
        },
      },

      rank: DataTypes.INTEGER,
      createdAt: {
        type: DataTypes.DATE,
      },
      updatedAt: {
        type: DataTypes.DATE,
      },
    },
    {
      sequelize,
      modelName: "Chapter",
    },
  );
  return Chapter;
};
